package com.example.dryyzx.controller;

import com.example.dryyzx.dao.BedMapper;
import com.example.dryyzx.dao.BedRecordMapper;
import com.example.dryyzx.dao.CustomerMapper;
import com.example.dryyzx.dao.UserMapper;
import com.example.dryyzx.encapsulation.CheckinPageEncapsulation;
import com.example.dryyzx.encapsulation.CheckinPageEncapsulation2;
import com.example.dryyzx.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class CustomerController {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private BedRecordMapper bedRecordMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BedRecordController bedRecordController;

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    public Bed searchBedInformationByBed_number(String bed_number){
        Bed bed=bedMapper.selectByBed_number(bed_number);
        return bed;
    }

    @RequestMapping(value = "checkin_page/add_new_person",method = RequestMethod.POST)
    public @ResponseBody String addCustomer(String name, String age, String gender, String identify_number, String room_number,
                                            String building_number, String bed_number, String type, String checkin_time, String contract_expiry_time,
                                            String marital_status,String height,String weight,String blood_type,String nursing_level,String tel, String remark)
                                            throws ParseException {
        Customer newCustomer = new Customer();
        newCustomer.setName(name);
        try {
            newCustomer.setAge(Integer.valueOf(age));
        }catch (Exception e){
            System.out.println("age输入错误");
        }
        newCustomer.setSex(gender);
        newCustomer.setIdNumber(identify_number);
        Bed bed = searchBedInformationByBed_number(bed_number);

        if(bed!=null){
            if(bed.getIsOccupied()){
                return new JsonResult(false,"该床位已经有人住").toString();
            }
            newCustomer.setBedId(bed.getId());
            bed.setIsOccupied(true);
            bedMapper.updateByPrimaryKeySelective(bed);
        }else{
            return new JsonResult(false,"床位号输入错误 没有该床").toString();
            //找不到床位号对应的id 即 没有这张床
        }
        newCustomer.setType(type);
        try {
            newCustomer.setCheckinTime(sdf.parse(checkin_time));
            newCustomer.setDueDate(sdf.parse(contract_expiry_time));
        }catch (ParseException e){
            System.out.println("checkin_time输入错误");
            return new JsonResult(false,"time input error").toString();
        }

        //校验身份证号位数
        if(identify_number.length() != 18){
            return new JsonResult(false,"身份证号位数出错").toString();
        }
        newCustomer.setNursingLevel(Integer.valueOf(nursing_level));
        newCustomer.setHeight(Float.valueOf(height));
        newCustomer.setWeight(Float.valueOf(weight));
        newCustomer.setBloodType(blood_type);
        newCustomer.setPhoneNumber(tel);
        newCustomer.setRemarks(remark);
        newCustomer.setMaritalStatus(marital_status);
        newCustomer.setArchivesid("BH"+checkin_time.substring(0,3)+identify_number.substring(14,17));

        customerMapper.insertSelective(newCustomer);
        int newid=customerMapper.selectLastId();    //获得最新的customer的数据
        bedRecordController.insertNewRecordByCustomer_idAndBed_id(newCustomer.getBedId(),newid,checkin_time);

        return new JsonResult(true,null).toString();
    }

    public @ResponseBody
    List<Bed> search_bed_by_customer(List<Customer> customer) {
        int i;
        List<Bed> bed = new ArrayList<Bed>();
        Bed bedtmp = null;
        for (i = 0; i < customer.size(); i++) {
            bedtmp = bedMapper.selectByPrimaryKey(customer.get(i).getBedId());
            bed.add(i, bedtmp);
        }
        return bed;
    }

    public @ResponseBody
    List<User> search_health_keeper_by_customer(List<Customer> customer) {
        int i;
        List<User> health_keeper = new ArrayList<User>();
        User usertmp = null;
        for (i = 0; i < customer.size(); i++) {
            usertmp = userMapper.selectByPrimaryKey(customer.get(i).getHealthKeeperId());
            health_keeper.add(i, usertmp);
        }
        return health_keeper;
    }

    List<CheckinPageEncapsulation> getEncapsulation(List<Customer> customer,List<Bed> bed,List<User> health_keeper,int limit){
        List<CheckinPageEncapsulation> encapsulation = new ArrayList<CheckinPageEncapsulation>();
        for (int i=0;i<limit;i++) {
            CheckinPageEncapsulation tmp = new CheckinPageEncapsulation();
            tmp.id = customer.get(i).getId();//老人编号
            tmp.name = customer.get(i).getName();//老人姓名
            tmp.gender = customer.get(i).getSex();//老人性别，限定为"男","女"
            tmp.age = customer.get(i).getAge();//老人年龄
            tmp.height = customer.get(i).getHeight();//身高
            tmp.weight = customer.get(i).getWeight();//体重
            tmp.blood_type = customer.get(i).getBloodType();//血型
            tmp.marital_status = customer.get(i).getMaritalStatus();//婚姻状况
            tmp.nursing_level = customer.get(i).getNursingLevel();//护理等级
            tmp.identify_number = customer.get(i).getIdNumber();//老人身份证号码
            tmp.room_number = bed.get(i).getRoomNumber();//老人房间号
            tmp.building_number = bed.get(i).getPosition();//老人楼栋号
            tmp.bed_number = bed.get(i).getBedNumber();//老人床号
            tmp.file_number = customer.get(i).getArchivesid();//文档编号
            tmp.checkin_time = sdf.format(customer.get(i).getCheckinTime());//入住时间
            tmp.contract_expiry_time = sdf.format(customer.get(i).getDueDate());//合同到期时间
            tmp.tel = customer.get(i).getPhoneNumber();//联系电话
            tmp.family_mumber_name = null;//家属名
            tmp.accompany_name = null;//陪住人
            tmp.evaluate_doctor = null;//评估医生
            tmp.in_charge_doctor = null;//负责医生
            tmp.care_workder = null;//护工
            tmp.health_keeper = health_keeper.get(i).getName();//健康管家
            tmp.remark = customer.get(i).getRemarks();//备注
            encapsulation.add(i, tmp);
        }
        return encapsulation;
    }

    @RequestMapping(value = "checkin_page/search_person_by_name", method = RequestMethod.POST)
    public @ResponseBody
    String search_person_by_name(String name, int page, HttpSession session) {
        int data_per_page = 10;
        int total_data_no = customerMapper.countByName(name);
        if(total_data_no<=0)
            return new JsonResult(false, "未查找到老人").toString();

        int offset=(page-1)*data_per_page;
        int limit;
        if(total_data_no-offset<data_per_page)
            limit=total_data_no-offset;
        else
            limit=data_per_page;
        if(total_data_no<=offset)
            return new JsonResult(false, "页数过大，数据不够").toString();

        List<Customer> customer = customerMapper.selectByLimitOffsetName(limit,offset,name);

        List<Bed> bed = search_bed_by_customer(customer);
        if (customer.size() != bed.size())
            return new JsonResult(false, "未查找到部分老人的床").toString();

        List<User> health_keeper = search_health_keeper_by_customer(customer);
        if (customer.size() != health_keeper.size())
            return new JsonResult(false, "未查找到部分老人的健康管家").toString();

        CheckinPageEncapsulation2 total_data=new CheckinPageEncapsulation2();
        List<CheckinPageEncapsulation> Encapsulation = getEncapsulation(customer,bed,health_keeper,limit);
        total_data.person_list=Encapsulation;
        total_data.total_page=(total_data_no-1)/data_per_page+1;

        return new JsonResult(true, total_data).toString();
    }

    @RequestMapping(value = "checkin_page/search_person_by_type", method = RequestMethod.POST)
    public @ResponseBody
    String search_person_by_type(String type, int page, HttpSession session) {
        int data_per_page = 10;
        int total_data_no = customerMapper.countByType(type);
        if (total_data_no <= 0)
            return new JsonResult(false, "未查找到老人").toString();

        int offset = (page - 1) * data_per_page;
        int limit;
        if (total_data_no - offset < data_per_page)
            limit = total_data_no - offset;
        else
            limit = data_per_page;
        if (total_data_no <= offset)
            return new JsonResult(false, "页数过大，数据不够").toString();

        List<Customer> customer = customerMapper.selectByLimitOffsetType( limit, offset,type);

        List<Bed> bed = search_bed_by_customer(customer);
        if (customer.size() != bed.size())
            return new JsonResult(false, "未查找到部分老人的床").toString();

        List<User> health_keeper = search_health_keeper_by_customer(customer);
        if (customer.size() != health_keeper.size())
            return new JsonResult(false, "未查找到部分老人的健康管家").toString();

        CheckinPageEncapsulation2 total_data=new CheckinPageEncapsulation2();
        List<CheckinPageEncapsulation> Encapsulation = getEncapsulation(customer,bed,health_keeper,limit);
        total_data.person_list=Encapsulation;
        total_data.total_page=(total_data_no-1)/data_per_page+1;

        return new JsonResult(true, total_data).toString();
    }

    @RequestMapping(value = "/checkin_page/change_detail", method = RequestMethod.POST)
    public @ResponseBody String updateCustomer(@RequestParam("id")String id, @RequestParam("name") String  name,
                                               @RequestParam("age")String age, @RequestParam("gender")String gender,
                                               @RequestParam("height")String height, @RequestParam("weight")String weight,
                                               @RequestParam("blood_type")String blood_type, @RequestParam("marital_status")String marital_status,
                                               @RequestParam("nursing_level")String nursing_level, @RequestParam("identify_number")String identify_number,
                                               @RequestParam("room_number")String room_number, @RequestParam("bed_number")String bed_number,
                                               @RequestParam("building_number")String building_number, @RequestParam("file_number")String file_number,
                                               @RequestParam("type")String type, @RequestParam("checkin_time")String checkin_time, @RequestParam("contract_expiry_time")String contract_expiry_time,
                                               @RequestParam("tel")String tel, @RequestParam("remark")String remark, HttpSession session)
    {
        Customer targetRecord =customerMapper.selectByPrimaryKey(Integer.valueOf(id));
        int oldBed_id= targetRecord.getBedId();
        //Date oldTime=targetRecord.getCheckinTime();
        targetRecord.setName(name);
        try {
            targetRecord.setAge(Integer.valueOf(age));
        }catch (Exception e){
            System.out.println("age输入错误");
        }
        targetRecord.setSex(gender);
        targetRecord.setIdNumber(identify_number);
        Bed bed = bedMapper.selectByBed_number(bed_number);
        Bed oldBed = bedMapper.selectByPrimaryKey(oldBed_id);
        if(bed!=null){
            targetRecord.setBedId(bed.getId());
            bed.setIsOccupied(true);
            oldBed.setIsOccupied(false);
            bedMapper.updateByPrimaryKeySelective(bed);
            bedMapper.updateByPrimaryKeySelective(oldBed);
        }else {
            return new JsonResult(false,"床位号输入错误 没有该床").toString();
            //找不到床位号对应的id 即 没有这张床
        }
        targetRecord.setType(type);
        targetRecord.setHeight(Float.valueOf(height));
        targetRecord.setWeight(Float.valueOf(weight));
        targetRecord.setBloodType(blood_type);
        targetRecord.setMaritalStatus(marital_status);
        targetRecord.setNursingLevel(Integer.valueOf(nursing_level));
        targetRecord.setPhoneNumber(tel);
        targetRecord.setRemarks(remark);
        targetRecord.setArchivesid(file_number);
        try {
            targetRecord.setCheckinTime(sdf.parse(checkin_time));
            targetRecord.setDueDate(sdf.parse(contract_expiry_time));
        }catch (ParseException e){
            System.out.println("checkin_time输入错误");
            return new JsonResult(false,"time input error").toString();
        }
        int updateCustomer = customerMapper.updateByPrimaryKeySelective(targetRecord);
        // 3、转（写接口，就是输出数据）
        if (updateCustomer != 0) {
            session.setAttribute("updateCustomer", updateCustomer);
            bedRecordController.deleteOldRecordByCustomer_idAndBed_id(targetRecord.getId(),oldBed_id,targetRecord.getCheckinTime());
            bedRecordController.insertNewRecordByCustomer_idAndBed_id(targetRecord.getBedId(),targetRecord.getId(),checkin_time);
            return new JsonResult(true, updateCustomer).toString();
        } else {
            return new JsonResult(false, "找不到要修改的老人！无法进行修改").toString();
        }
    }

    /*@RequestMapping(value = "/checkin_page/delete_person_by_id", method = RequestMethod.POST)
    public @ResponseBody String deleteCustomer(String id,HttpSession session) {
        Customer deleteRecord = new Customer();
        deleteRecord.setId(Integer.valueOf(id));
        deleteRecord.setState("已退住");
        int deleteCustomer = customerMapper.updateByPrimaryKeySelective(deleteRecord);
        if (deleteCustomer != 0) {
            session.setAttribute("deleteCustomer", deleteCustomer);
            return new JsonResult(true, deleteCustomer).toString();
        } else {
            return new JsonResult(false, "找不到要删除的老人！无法进行删除").toString();
        }
    }*/
}
